// 全局变量
let map;
let drawnItems;
let selectedArea = null;
let activeTasks = {};
let refreshInterval = null;

// 初始化地图
function initMap() {
    // 创建地图
    map = L.map('map').setView([30.5, 122.5], 7);

    // 默认图层
    defaultLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 19
    }).addTo(map);

    // 添加常用海域预设范围
    const presets = {
        '中国东海': [
            [28, 121],
            [33, 126]
        ],
        '日本海域': [
            [31, 137],
            [45, 145]
        ],
        '南海': [
            [4, 108],
            [22, 118]
        ]
    };

    // 添加预设菜单到地图
    const presetsControl = L.control({ position: 'topright' });
    presetsControl.onAdd = function() {
            const div = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
            div.innerHTML = `
            <a href="#" title="常用海域预设" style="font-weight: bold; font-size: 14px; display: flex; align-items: center; justify-content: center;">🌊</a>
            <div class="preset-menu" style="display: none; position: absolute; right: 0; background: white; border: 1px solid #ccc; padding: 5px; z-index: 1000; border-radius: 4px; min-width: 150px; max-width: 200px;">
                <p class="text-xs font-medium mb-1 text-gray-700" style="margin: 0 0 5px 0; padding-bottom: 3px; border-bottom: 1px solid #eee;">海域快速选择</p>
                ${Object.keys(presets).map(name => `
                    <div class="preset-item" data-name="${name}" style="padding: 5px; cursor: pointer; white-space: nowrap; margin-bottom: 2px;">
                        <span style="margin-right: 3px;">${name === '中国东海' ? '🇨🇳' : name === '日本海域' ? '🇯🇵' : '🌏'}</span> ${name}
                    </div>
                `).join('')}
            </div>
        `;
        
        // 显示/隐藏菜单
        const link = div.querySelector('a');
        const menu = div.querySelector('.preset-menu');
        
        L.DomEvent.on(link, 'click', function(e) {
            L.DomEvent.preventDefault(e);
            e.stopPropagation();
            menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
        });
        
        // 点击其他地方关闭菜单
        L.DomEvent.on(document, 'click', function() {
            menu.style.display = 'none';
        });
        
        // 阻止菜单点击事件冒泡
        L.DomEvent.on(menu, 'click', function(e) {
            e.stopPropagation();
        });
        
        // 点击预设项
        const items = div.querySelectorAll('.preset-item');
        items.forEach(item => {
            L.DomEvent.on(item, 'click', function() {
                const name = this.getAttribute('data-name');
                const bounds = presets[name];
                if (bounds) {
                    // 清除现有区域
                    drawnItems.clearLayers();
                    
                    // 创建矩形
                    const rectangle = L.rectangle([
                        [bounds[0][0], bounds[0][1]],
                        [bounds[1][0], bounds[1][1]]
                    ], {
                        color: '#2196F3',
                        weight: 2
                    });
                    
                    drawnItems.addLayer(rectangle);
                    selectedArea = rectangle.getBounds();
                    
                    // 更新输入框
                    updateCoordinateInputs(selectedArea);
                    
                    // 调整视图
                    map.fitBounds(selectedArea);
                    
                    // 关闭菜单
                    menu.style.display = 'none';
                    
                    // 根据海域类型设置建议的瓦片源
                    let recommendedSource = 'osm';
                    if (name === '日本海域') {
                        recommendedSource = 'google_satellite';
                    } else if (name === '中国东海') {
                        recommendedSource = 'esri_ocean';
                    } else if (name === '南海') {
                        recommendedSource = 'google_satellite';
                    }
                    
                    const currentSource = document.getElementById('tileSource').value;
                    // 只有当前选择不是海域专用源时，才提示切换
                    if (currentSource !== 'esri_ocean' && currentSource !== 'google_satellite' && 
                        currentSource !== 'esri' && currentSource !== 'google_hybrid') {
                        if (confirm(`为了更好地显示海域地图，建议使用海域专用瓦片源\n\n是否切换到推荐瓦片源: ${
                            recommendedSource === 'esri_ocean' ? 'ESRI海洋' : 
                            recommendedSource === 'google_satellite' ? 'Google卫星' : 
                            recommendedSource
                        }？`)) {
                            document.getElementById('tileSource').value = recommendedSource;
                        }
                    }
                }
            });
        });
        
        return div;
    };
    presetsControl.addTo(map);

    // 创建绘图图层
    drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);

    // 绘图控件
    const drawControl = new L.Control.Draw({
        draw: {
            polyline: false,
            polygon: false,
            circle: false,
            marker: false,
            circlemarker: false,
            rectangle: {
                shapeOptions: {
                    color: '#2196F3'
                }
            }
        },
        edit: {
            featureGroup: drawnItems,
            remove: true
        }
    });
    map.addControl(drawControl);

    // 绘图事件
    map.on(L.Draw.Event.CREATED, function(event) {
        drawnItems.clearLayers();
        const layer = event.layer;
        drawnItems.addLayer(layer);
        selectedArea = layer.getBounds();
        updateCoordinateInputs(selectedArea);
    });

    map.on(L.Draw.Event.DELETED, function() {
        selectedArea = null;
        clearCoordinateInputs();
    });
}

// 更新坐标输入框
function updateCoordinateInputs(bounds) {
    document.getElementById('minLat').value = bounds.getSouth().toFixed(6);
    document.getElementById('minLon').value = bounds.getWest().toFixed(6);
    document.getElementById('maxLat').value = bounds.getNorth().toFixed(6);
    document.getElementById('maxLon').value = bounds.getEast().toFixed(6);
}

// 清除坐标输入框
function clearCoordinateInputs() {
    document.getElementById('minLat').value = '';
    document.getElementById('minLon').value = '';
    document.getElementById('maxLat').value = '';
    document.getElementById('maxLon').value = '';
}

// 从输入框获取坐标并绘制区域
function drawAreaFromInputs() {
    const minLat = parseFloat(document.getElementById('minLat').value);
    const minLon = parseFloat(document.getElementById('minLon').value);
    const maxLat = parseFloat(document.getElementById('maxLat').value);
    const maxLon = parseFloat(document.getElementById('maxLon').value);

    // 验证输入
    if (isNaN(minLat) || isNaN(minLon) || isNaN(maxLat) || isNaN(maxLon)) {
        alert('请输入有效的经纬度值');
        return;
    }

    // 创建边界矩形
    const bounds = L.latLngBounds(
        L.latLng(minLat, minLon),
        L.latLng(maxLat, maxLon)
    );

    // 清除之前的图层
    drawnItems.clearLayers();

    // 创建新的矩形图层
    const rectangle = L.rectangle(bounds, {
        color: '#2196F3',
        weight: 2
    });
    drawnItems.addLayer(rectangle);
    selectedArea = bounds;

    // 调整地图视图
    map.fitBounds(bounds);
}

// 计算下载区域的瓦片数量和大小
function calculateDownloadSize() {
    if (!selectedArea) {
        alert('请先选择下载区域');
        return;
    }

    const minLat = selectedArea.getSouth();
    const minLon = selectedArea.getWest();
    const maxLat = selectedArea.getNorth();
    const maxLon = selectedArea.getEast();
    const minZoom = parseInt(document.getElementById('minZoom').value);
    const maxZoom = parseInt(document.getElementById('maxZoom').value);

    // 计算每个缩放级别的瓦片数量
    let totalTiles = 0;
    let sizeMB = 0;
    const avgTileSize = 15; // 假设每个瓦片平均15KB

    for (let z = minZoom; z <= maxZoom; z++) {
        // 计算该缩放级别下的瓦片范围
        const minX = Math.floor((minLon + 180) / 360 * Math.pow(2, z));
        const maxX = Math.floor((maxLon + 180) / 360 * Math.pow(2, z));

        const minY = Math.floor((1 - Math.log(Math.tan(maxLat * Math.PI / 180) + 1 / Math.cos(maxLat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z));
        const maxY = Math.floor((1 - Math.log(Math.tan(minLat * Math.PI / 180) + 1 / Math.cos(minLat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z));

        const tilesAtZoom = (maxX - minX + 1) * (maxY - minY + 1);
        totalTiles += tilesAtZoom;
    }

    sizeMB = (totalTiles * avgTileSize) / 1024;

    // 显示结果
    alert(`估计下载信息:
- 总瓦片数量: ${totalTiles.toLocaleString()}
- 预计大小: ${sizeMB.toFixed(2)} MB
- 缩放级别: ${minZoom} - ${maxZoom}`);
}

// 获取当前选择的瓦片URL模板
function getTileUrlTemplate() {
    const tileSource = document.getElementById('tileSource').value;

    switch (tileSource) {
        case 'osm':
            return 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
        case 'otm':
            return 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png';
        case 'esri':
            return 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
        case 'esri_ocean':
            return 'https://server.arcgisonline.com/ArcGIS/rest/services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}';
        case 'carto':
            return 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png';
        case 'google':
            return 'https://mt{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}';
        case 'google_satellite':
            return 'https://mt{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}';
        case 'google_terrain':
            return 'https://mt{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}';
        case 'google_hybrid':
            return 'https://mt{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}';
        case 'custom':
            return document.getElementById('customTileUrl').value;
        default:
            return 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    }
}

// 显示/隐藏自定义瓦片URL输入框
function toggleCustomTileUrl() {
    const container = document.getElementById('customTileUrlContainer');
    if (document.getElementById('tileSource').value === 'custom') {
        container.classList.remove('hidden');
    } else {
        container.classList.add('hidden');
    }
}

// 开始下载地图区域
function startDownload() {
    if (!selectedArea) {
        alert('请先选择下载区域');
        return;
    }

    // 获取经纬度范围并确保精度足够
    const minLat = parseFloat(selectedArea.getSouth().toFixed(6));
    const minLon = parseFloat(selectedArea.getWest().toFixed(6));
    const maxLat = parseFloat(selectedArea.getNorth().toFixed(6));
    const maxLon = parseFloat(selectedArea.getEast().toFixed(6));

    // 检查经纬度范围是否有效
    if (minLat >= maxLat || minLon >= maxLon) {
        alert('经纬度范围无效，请重新选择区域');
        return;
    }

    // 检查选择的区域面积是否过大
    const latDiff = maxLat - minLat;
    const lonDiff = maxLon - minLon;
    if (latDiff > 10 || lonDiff > 10) {
        if (!confirm('您选择的区域范围过大，可能导致下载时间过长或失败。\n建议选择更小的区域。\n\n是否继续？')) {
            return;
        }
    }

    // 检查是否是海域
    // 更复杂的海域判断逻辑，覆盖中国不同沿海区域
    const isEastChinaSea = minLon > 118 && maxLon < 125 && minLat > 25 && maxLat < 35; // 东海
    const isYellowSea = minLon > 118 && maxLon < 127 && minLat > 32 && maxLat < 41;    // 黄海
    const isSouthChinaSea = minLon > 108 && maxLon < 120 && minLat > 3 && maxLat < 25; // 南海
    const isBohaiBay = minLon > 117 && maxLon < 122 && minLat > 37 && maxLat < 41;     // 渤海
    
    const isMainlyOcean = isEastChinaSea || isYellowSea || isSouthChinaSea || isBohaiBay;

    // 当前选择的瓦片源
    const currentSource = document.getElementById('tileSource').value;
    
    // 为海域推荐更适合的瓦片源
    if (isMainlyOcean && (currentSource === 'osm' || currentSource === 'otm' || currentSource === 'carto')) {
        const recommended = isEastChinaSea ? 'esri_ocean' : 'google_satellite';
        if (confirm(`您选择的区域主要是海域，当前瓦片源(${currentSource})对海域数据支持有限。\n\n推荐使用${recommended === 'esri_ocean' ? 'ESRI Ocean' : 'Google卫星图'}瓦片源，是否切换？`)) {
            document.getElementById('tileSource').value = recommended;
        }
    }

    const minZoom = parseInt(document.getElementById('minZoom').value);
    const maxZoom = parseInt(document.getElementById('maxZoom').value);
    const mapName = document.getElementById('mapName').value || `Map_${minLat.toFixed(2)}_${minLon.toFixed(2)}`;
    const tileUrl = getTileUrlTemplate();

    // 输出调试信息到控制台，帮助排查问题
    console.log('下载参数:', {
        minLat,
        minLon,
        maxLat,
        maxLon,
        minZoom,
        maxZoom,
        mapName,
        tileUrl
    });

    // 根据区域大小和缩放级别预估下载量
    let tilesCount = 0;
    for (let z = minZoom; z <= maxZoom; z++) {
        const minX = Math.floor((minLon + 180) / 360 * Math.pow(2, z));
        const maxX = Math.floor((maxLon + 180) / 360 * Math.pow(2, z));
        const minY = Math.floor((1 - Math.log(Math.tan(maxLat * Math.PI / 180) + 1 / Math.cos(maxLat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z));
        const maxY = Math.floor((1 - Math.log(Math.tan(minLat * Math.PI / 180) + 1 / Math.cos(minLat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z));
        tilesCount += (maxX - minX + 1) * (maxY - minY + 1);
    }

    // 如果瓦片数量过多，警告用户
    if (tilesCount > 10000) {
        if (!confirm(`警告: 该区域将下载约 ${tilesCount.toLocaleString()} 个瓦片，可能需要较长时间。\n推荐的做法:\n- 减小区域范围\n- 降低最大缩放级别\n\n确定要继续吗？`)) {
            return;
        }
    }

    // 准备请求数据
    const data = {
        minLat,
        minLon,
        maxLat,
        maxLon,
        minZoom,
        maxZoom,
        name: mapName,
        description: `${mapName} (${minLat.toFixed(4)},${minLon.toFixed(4)}) - (${maxLat.toFixed(4)},${maxLon.toFixed(4)})`,
        tileUrl: tileUrl
    };

    // 发送下载请求
    fetch('/api/download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.taskId) {
                // 添加任务到列表
                activeTasks[result.taskId] = {
                    id: result.taskId,
                    status: 'started',
                    progress: 0
                };

                // 确保定时刷新已启动
                if (!refreshInterval) {
                    refreshInterval = setInterval(refreshTasks, 2000);
                }

                // 刷新任务列表
                displayTasks();
                alert(`下载任务已启动 (ID: ${result.taskId})`);
            } else {
                alert('启动下载任务失败: ' + (result.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('请求失败: ' + error.message);
        });
}

// 刷新任务状态
function refreshTasks() {
    // 获取所有任务状态
    fetch('/api/tasks')
        .then(response => response.json())
        .then(tasks => {
            let hasActiveTasks = false;

            // 更新任务状态
            tasks.forEach(task => {
                activeTasks[task.id] = task;
                if (task.status === 'downloading' || task.status === 'converting' || task.status === 'preparing') {
                    hasActiveTasks = true;
                }
            });

            // 如果没有活动任务，停止刷新
            if (!hasActiveTasks && Object.keys(activeTasks).length > 0) {
                clearInterval(refreshInterval);
                refreshInterval = null;
            }

            // 更新任务显示
            displayTasks();
        })
        .catch(error => {
            console.error('Error refreshing tasks:', error);
        });

    // 刷新MBTiles文件列表
    loadMBTilesList();
}

// 显示任务列表
function displayTasks() {
    const tasksList = document.getElementById('tasksList');

    if (Object.keys(activeTasks).length === 0) {
        tasksList.innerHTML = '<p class="text-gray-500 text-center">暂无下载任务</p>';
        return;
    }

    tasksList.innerHTML = '';

    // 按ID排序
    const sortedTasks = Object.values(activeTasks).sort((a, b) => b.id - a.id);

    sortedTasks.forEach(task => {
        const taskItem = document.createElement('div');
        taskItem.className = `task-item ${task.status}`;

        // 计算进度
        let progress = 0;
        let progressText = "0.0%";
        if (task.total_tiles > 0) {
            progress = (task.downloaded_tiles / task.total_tiles) * 100;
            progressText = `${progress.toFixed(1)}%`;
        } else if (task.status === 'failed' && (!task.total_tiles || task.total_tiles === 0)) {
            progressText = "0.0%";
        }

        // 格式化状态
        let statusText = '准备中';
        let statusClass = 'bg-gray-200';

        if (task.status === 'downloading') {
            statusText = '下载中';
            statusClass = 'bg-blue-200 text-blue-800';
        } else if (task.status === 'converting') {
            statusText = '转换中';
            statusClass = 'bg-yellow-200 text-yellow-800';
        } else if (task.status === 'completed') {
            statusText = '已完成';
            statusClass = 'bg-green-200 text-green-800';
        } else if (task.status === 'failed') {
            statusText = '失败';
            statusClass = 'bg-red-200 text-red-800';
        }

        // 计算时间
        let timeText = '';
        if (task.start_time) {
            const startTime = new Date(task.start_time * 1000);
            timeText = `开始: ${startTime.toLocaleString()}`;

            if (task.end_time) {
                const endTime = new Date(task.end_time * 1000);
                const duration = (task.end_time - task.start_time) / 60;
                timeText += ` | 结束: ${endTime.toLocaleString()} | 用时: ${duration.toFixed(1)}分钟`;
            }
        }
        
        // 显示使用的瓦片源信息
        let sourceInfo = '';
        if (task.source_type_used) {
            const sourceName = {
                'osm': 'OpenStreetMap',
                'esri': 'ESRI卫星',
                'esri_ocean': 'ESRI海洋图',
                'google': 'Google地图',
                'google_satellite': 'Google卫星',
                'google_hybrid': 'Google混合',
                'otm': 'OpenTopoMap',
                'carto': 'CartoDB'
            }[task.source_type_used] || task.source_type_used;
            
            sourceInfo = `<div class="mt-1 text-xs">使用瓦片源: <span class="font-medium">${sourceName}</span></div>`;
        }

        // 如果下载失败且没有瓦片，显示诊断提示
        let diagnosticTip = '';
        if (task.status === 'failed') {
            // 根据不同的错误提供不同的诊断建议
            let recommendedSources = ['ESRI Ocean', 'Google Satellite'];
            
            if (task.error && task.error.includes('无法计算有效瓦片')) {
                recommendedSources = ['ESRI Ocean', 'Google Satellite']; // 海域建议
            } else if (task.error && task.error.includes('格式')) {
                recommendedSources = ['ESRI World Imagery', 'Google Maps']; // 格式错误
            }
            
            diagnosticTip = `
            <div class="mt-2 text-xs bg-yellow-50 p-2 rounded border border-yellow-200">
                <p class="font-medium text-yellow-700">诊断信息:</p>
                <ul class="list-disc list-inside text-yellow-700">
                    <li>检查所选区域是否在有效的地图覆盖范围内</li>
                    <li>尝试切换瓦片源: <span class="font-medium">${recommendedSources.join('</span> 或 <span class="font-medium">')}</span></li>
                    <li>可以使用命令行修复工具: <span class="font-mono">fix_download_tasks.bat ${task.id}</span></li>
                </ul>
            </div>`;
        }

        taskItem.innerHTML = `
        <div class="flex justify-between items-center">
            <span class="font-medium">任务 #${task.id}</span>
            <span class="text-sm ${statusClass} px-2 py-1 rounded">${statusText}</span>
        </div>
        <div class="mt-2 text-sm text-gray-600">
            ${task.output_file ? `文件: ${task.output_file}` : ''}
            ${task.error ? `<div class="text-red-500">错误: ${task.error}</div>` : ''}
        </div>
        ${sourceInfo}
        <div class="progress-bar mt-2">
            <div class="progress-bar-inner" style="width: ${progress.toFixed(1)}%"></div>
        </div>
        <div class="mt-1 text-xs text-gray-500 flex justify-between">
            <span>${task.downloaded_tiles || 0}/${task.total_tiles || 0} 瓦片 (${progressText})</span>
            <span>${task.failed_tiles || 0} 失败</span>
        </div>
        <div class="mt-1 text-xs text-gray-500">
            ${timeText}
        </div>
        ${diagnosticTip}
        ${task.status === 'failed' ? 
            `<div class="mt-2">
                <button class="retry-task text-xs px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600" data-task-id="${task.id}">
                    重试任务
                </button>
            </div>` : ''}
    `;
        
        tasksList.appendChild(taskItem);
    });
    
    // 为"重试任务"按钮添加事件监听器
    document.querySelectorAll('.retry-task').forEach(button => {
        button.addEventListener('click', function() {
            const taskId = this.getAttribute('data-task-id');
            retryTask(taskId);
        });
    });
}

// 加载MBTiles文件列表
function loadMBTilesList() {
    fetch('/api/mbtiles')
        .then(response => response.json())
        .then(files => {
            const mbtilesList = document.getElementById('mbtilesList');
            
            if (files.length === 0) {
                mbtilesList.innerHTML = '<p class="text-gray-500 text-center">暂无地图文件</p>';
                return;
            }
            
            mbtilesList.innerHTML = '';
            
            // 按创建时间排序
            files.sort((a, b) => b.created - a.created);
            
            files.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'bg-gray-50 p-4 rounded-md';
                
                const createdDate = new Date(file.created * 1000);
                
                fileItem.innerHTML = `
                    <div class="flex justify-between items-center">
                        <span class="font-medium">${file.name}</span>
                        <span class="text-sm">${file.size.toLocaleString()} KB</span>
                    </div>
                    <div class="text-xs text-gray-500 mt-1">
                        创建: ${createdDate.toLocaleString()}
                    </div>
                    <div class="mt-3 flex space-x-2">
                        <button class="download-mbtiles text-xs px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600" data-file="${file.file}">
                            下载
                        </button>
                        <button class="view-mbtiles text-xs px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600" data-file="${file.file}">
                            查看
                        </button>
                        <button class="delete-mbtiles text-xs px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600" data-file="${file.file}">
                            删除
                        </button>
                    </div>
                `;
                
                mbtilesList.appendChild(fileItem);
            });
            
            // 添加事件监听
            document.querySelectorAll('.download-mbtiles').forEach(button => {
                button.addEventListener('click', downloadMBTilesFile);
            });
            
            document.querySelectorAll('.view-mbtiles').forEach(button => {
                button.addEventListener('click', viewMBTilesFile);
            });
            
            document.querySelectorAll('.delete-mbtiles').forEach(button => {
                button.addEventListener('click', deleteMBTilesFile);
            });
        })
        .catch(error => {
            console.error('Error loading MBTiles list:', error);
        });
}

// 下载MBTiles文件
function downloadMBTilesFile(event) {
    const filename = event.target.getAttribute('data-file');
    window.location.href = `/api/mbtiles/${filename}`;
}

// 查看MBTiles文件
function viewMBTilesFile(event) {
    const filename = event.target.getAttribute('data-file');
    
    // 显示模态框
    const modal = document.getElementById('viewMapModal');
    modal.classList.remove('hidden');
    
    // 初始化离线地图
    const offlineMap = L.map('offlineMap').setView([30.5, 122.5], 7);
    
    // 使用在线底图（实际应用中应改为离线加载MBTiles）
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 19
    }).addTo(offlineMap);
    
    // 注意：实际加载MBTiles文件需要特殊的处理，这里仅为示例
    setTimeout(() => offlineMap.invalidateSize(), 100);
    
    // 关闭模态框
    document.getElementById('closeViewMapModal').addEventListener('click', () => {
        modal.classList.add('hidden');
        offlineMap.remove();
    });
}

// 删除MBTiles文件
function deleteMBTilesFile(event) {
    const filename = event.target.getAttribute('data-file');
    
    if (confirm(`确定要删除文件 "${filename}"吗？`)) {
        fetch(`/api/mbtiles/${filename}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                loadMBTilesList();
                alert('文件删除成功');
            } else {
                alert('删除失败: ' + (result.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('Error deleting file:', error);
            alert('删除请求失败: ' + error.message);
        });
    }
}

// 重试失败的任务
function retryTask(taskId) {
    if (!confirm(`确定要重试任务 #${taskId} 吗？\n\n建议选择不同的瓦片源。`)) {
        return;
    }
    
    // 先获取任务详情
    fetch(`/api/tasks/${taskId}`)
        .then(response => response.json())
        .then(task => {
            if (!task || task.error === '任务不存在') {
                alert('无法获取任务信息');
                return;
            }
            
            // 根据区域自动推荐最佳的瓦片源
            let recommendedSource = 'esri_ocean';
            const minLat = task.params?.min_lat;
            const minLon = task.params?.min_lon;
            const maxLat = task.params?.max_lat;
            const maxLon = task.params?.max_lon;
            
            // 检查是否是海域
            // 中国东部沿海和东海区域
            const isEastChinaSea = (minLon > 118 && maxLon < 125 && minLat > 25 && maxLat < 35);
            // 黄海区域
            const isYellowSea = (minLon > 118 && maxLon < 127 && minLat > 32 && maxLat < 41);
            // 南海区域
            const isSouthChinaSea = (minLon > 108 && maxLon < 120 && minLat > 3 && maxLat < 25);
            // 日本海域
            const isJapanSea = (minLon > 130 && maxLon < 150 && minLat > 30 && maxLat < 46);
            
            const isOceanArea = isEastChinaSea || isYellowSea || isSouthChinaSea || isJapanSea;
            
            // 获取原始使用的源和建议源
            const originalSource = task.params?.source_type;
            const sourceInfo = task.params?.source_info || {};
            
            // 避免重复使用同一个瓦片源
            const sourcesToExclude = [originalSource];
            if (task.source_type_used) {
                sourcesToExclude.push(task.source_type_used);
            }
            
            // 获取备选源列表
            let recommendedSources = [];
            
            if (isOceanArea) {
                if (isEastChinaSea || isYellowSea) {
                    recommendedSources = ['esri_ocean', 'google_satellite', 'esri', 'google_hybrid'];
                } else if (isJapanSea) {
                    recommendedSources = ['google_satellite', 'esri_ocean', 'esri'];
                } else {
                    recommendedSources = ['google_satellite', 'esri', 'google_hybrid', 'esri_ocean'];
                }
            } else {
                recommendedSources = ['esri', 'google', 'google_satellite', 'osm'];
            }
            
            // 过滤掉已尝试过的源
            recommendedSources = recommendedSources.filter(source => !sourcesToExclude.includes(source));
            
            // 如果所有建议的源都尝试过，返回原始列表
            if (recommendedSources.length === 0) {
                recommendedSources = ['esri_ocean', 'google_satellite', 'esri', 'google', 'osm'];
            }
            
            // 选择第一个推荐的源
            recommendedSource = recommendedSources[0];
            
            // 询问用户选择瓦片源
            const sources = {
                'esri_ocean': 'ESRI海洋 (海域专用)',
                'google_satellite': 'Google卫星 (海域效果好)',
                'google_hybrid': 'Google混合 (卫星+标注)',
                'esri': 'ESRI卫星影像',
                'google': 'Google地图',
                'osm': 'OpenStreetMap',
                'otm': 'OpenTopoMap',
                'carto': 'CartoDB轻量版'
            };
            
            // 将推荐源放在前面
            const sortedSources = {};
            recommendedSources.forEach(source => {
                if (sources[source]) {
                    sortedSources[source] = sources[source];
                }
            });
            
            // 添加其他未推荐的源
            Object.keys(sources).forEach(source => {
                if (!sortedSources[source]) {
                    sortedSources[source] = sources[source];
                }
            });
            
            const sourceOptions = Object.entries(sortedSources)
                .map(([value, name]) => `<option value="${value}" ${value === recommendedSource ? 'selected' : ''}>${name}</option>`)
                .join('');
            
            // 创建一个临时对话框供用户选择瓦片源
            const dialog = document.createElement('div');
            dialog.innerHTML = `
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-md">
                        <h3 class="text-xl font-semibold mb-4">重试任务 #${taskId}</h3>
                        <p class="mb-2">原始区域: ${minLat.toFixed(4)}, ${minLon.toFixed(4)} 至 ${maxLat.toFixed(4)}, ${maxLon.toFixed(4)}</p>
                        <p class="mb-4">请选择要使用的瓦片源:</p>
                        <select id="retryTileSource" class="w-full p-2 border rounded mb-4">
                            ${sourceOptions}
                        </select>
                        ${isOceanArea ? `<p class="text-sm text-yellow-600 mb-4">⚠️ 检测到选定区域为海域区域，推荐使用海域专用瓦片源</p>` : ''}
                        <div class="flex justify-end space-x-2">
                            <button id="cancelRetry" class="px-4 py-2 bg-gray-300 rounded hover:bg-gray-400">取消</button>
                            <button id="confirmRetry" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">确认重试</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(dialog);
            
            // 设置事件处理
            document.getElementById('cancelRetry').addEventListener('click', () => {
                document.body.removeChild(dialog);
            });
            
            document.getElementById('confirmRetry').addEventListener('click', () => {
                const selectedSource = document.getElementById('retryTileSource').value;
                document.body.removeChild(dialog);
                
                // 调用修复API
                fetch('/api/retry_task', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        taskId: parseInt(taskId),
                        sourceType: selectedSource
                    })
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        alert(`任务 #${taskId} 已重新启动，使用 ${selectedSource} 瓦片源`);
                        // 刷新任务列表
                        if (!refreshInterval) {
                            refreshInterval = setInterval(refreshTasks, 2000);
                        }
                        refreshTasks();
                    } else {
                        alert(`重试失败: ${result.error || '未知错误'}`);
                    }
                })
                .catch(error => {
                    console.error('Error retrying task:', error);
                    alert('重试请求失败。您可以尝试使用命令行工具重试:\nfix_download_tasks.bat ' + taskId);
                });
            });
        })
        .catch(error => {
            console.error('Error fetching task details:', error);
            alert('获取任务详情失败');
        });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化地图
    initMap();
    
    // 加载MBTiles文件列表
    loadMBTilesList();
    
    // 监听坐标输入变化
    document.getElementById('minLat').addEventListener('change', drawAreaFromInputs);
    document.getElementById('minLon').addEventListener('change', drawAreaFromInputs);
    document.getElementById('maxLat').addEventListener('change', drawAreaFromInputs);
    document.getElementById('maxLon').addEventListener('change', drawAreaFromInputs);
    
    // 监听瓦片源变化
    document.getElementById('tileSource').addEventListener('change', toggleCustomTileUrl);
    
    // 监听按钮点击
    document.getElementById('calculateSize').addEventListener('click', calculateDownloadSize);
    document.getElementById('downloadBtn').addEventListener('click', startDownload);
    
    // 刷新任务状态
    refreshTasks();
});